import { defineEventHandler } from 'h3'
import { query } from '../utils/db'
import type { AboutUs, AboutData } from '~/types/about';
import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'



export default defineEventHandler(async (event) => {
  const method = event.node.req.method
  if (method === 'GET') {
    try {
      const { results } = await query(`
    SELECT 
      section_type as type,
      title,
      content,
      year,
      icon_class as icon,
      bg_color as bg,
      text_color as textColor
    FROM about_us
    ORDER BY section_type, sort_order
  `)

      // 按类型分组数据
      const groupedData = results.reduce((acc: { [x: string]: any[] }, item: { type: string | number }) => {
        if (!acc[item.type]) {
          acc[item.type] = []
        }
        acc[item.type].push(item)
        return acc
      }, {})

      return sendSuccessResponse(event, {
        logo: groupedData.logo?.[0]?.content || '',
        title: groupedData.title?.[0]?.content || '',
        intro: groupedData.intro?.[0]?.content || '',
        visionMission: groupedData.vision_mission || [],
        milestones: groupedData.milestone || [],
        cultures: groupedData.culture || []
      }, '关于我们获取成功')
    } catch (error: any) {
      return sendErrorResponse(event, ResponseCode.BAD_REQUEST, error?.message || '获取关于我们信息失败')

    }
  } else if (method === 'PUT') {
    const data = await readBody<AboutUs>(event);
    // 清空表
    await execute('TRUNCATE TABLE about_us');
    try {
      if (data) {
        // 准备批量插入数据
        const insertPromises = [];

        // 处理标题、logo和简介
        if (data.logo) {
          insertPromises.push(
            execute(
              'INSERT INTO about_us (section_type, content) VALUES (?, ?)',
              ['logo', data.logo]
            )
          );
        }

        if (data.title) {
          insertPromises.push(
            execute(
              'INSERT INTO about_us (section_type, content) VALUES (?, ?)',
              ['title', data.title]
            )
          );
        }

        if (data.intro) {
          insertPromises.push(
            execute(
              'INSERT INTO about_us (section_type, content) VALUES (?, ?)',
              ['intro', data.intro]
            )
          );
        }

        // 处理文化部分
        if (data.cultures && data.cultures.length > 0) {
          const cultureValues = data.cultures.map(culture => [
            'culture',
            culture.title || '',
            culture.content || '',
            culture.icon_class || '',
            culture.bgColor || '',
            culture.textColor || '',
            culture.sort_order || 0
          ]);

          insertPromises.push(
            execute(
              `INSERT INTO about_us 
          (section_type, title, content, icon_class, bg_color, text_color, sort_order) 
          VALUES ?`,
              [cultureValues]
            )
          );
        }

        // 处理里程碑部分
        if (data.milestones && data.milestones.length > 0) {
          const milestoneValues = data.milestones.map(milestone => [
            'milestone',
            milestone.title || '',
            milestone.content || '',
            milestone.year || '',
            milestone.icon_class || '',
            milestone.bgColor || '',
            milestone.textColor || '',
            milestone.sort_order || 0
          ]);

          insertPromises.push(
            execute(
              `INSERT INTO about_us 
          (section_type, title, content, year, icon_class, bg_color, text_color, sort_order) 
          VALUES ?`,
              [milestoneValues]
            )
          );
        }

        // 处理愿景与使命部分
        if (data.visionMission && data.visionMission.length > 0) {
          const visionMissionValues = data.visionMission.map(vision => [
            'vision_mission',
            vision.title || '',
            vision.content || '',
            vision.iconClass || '',
            vision.bgColor || '',
            vision.textColor || '',
            vision.sort_order || 0
          ]);

          insertPromises.push(
            execute(
              `INSERT INTO about_us 
          (section_type, title, content, icon_class, bg_color, text_color, sort_order) 
          VALUES ?`,
              [visionMissionValues]
            )
          );
        }

        // 执行所有插入操作
        await Promise.all(insertPromises);
        return sendSuccessResponse(event, {
          success: true
        }, '关于我们更新成功')

      }
    } catch (error: any) {
      console.error('Error inserting about us data:', error);
      return sendErrorResponse(event, ResponseCode.BAD_REQUEST, error?.message || '更新关于我们信息失败')
    }
  }

})